package com.tzkyzj.tiremanager.contorller;

import com.tzkyzj.tiremanager.entity.TirePhoto;
import com.tzkyzj.tiremanager.service.TirePhotoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;

@RestController  // 改为 @RestController 简化返回JSON数据
@RequestMapping("/api/tires")
public class TirePhotoController {

    private final TirePhotoService tirePhotoService;

    // 使用构造器注入
    public TirePhotoController(TirePhotoService tirePhotoService) {
        this.tirePhotoService = tirePhotoService;
    }

    // 上传照片 - 修复版本
    @PostMapping("/{id}/photos")
    public ResponseEntity<?> uploadPhotos(
            @PathVariable Long id,
            @RequestParam("photos") MultipartFile[] files) {

        try {
            System.out.println("开始上传照片，轮胎ID: " + id);
            System.out.println("接收到的文件数量: " + files.length);

            // 验证文件
            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    return ResponseEntity.badRequest().body("文件不能为空");
                }

                if (!file.getContentType().startsWith("image/")) {
                    return ResponseEntity.badRequest().body("只能上传图片文件");
                }

                if (file.getSize() > 5 * 1024 * 1024) { // 5MB限制
                    return ResponseEntity.badRequest().body("文件大小不能超过5MB");
                }

                System.out.println("文件验证通过: " + file.getOriginalFilename() + ", 大小: " + file.getSize());
            }

            // 使用专门的照片服务方法
            List<TirePhoto> savedPhotos = tirePhotoService.savePhotos(id, files);
            System.out.println("照片保存完成，保存了 " + savedPhotos.size() + " 张照片到数据库");

            return ResponseEntity.ok(savedPhotos);

        } catch (Exception e) {
            System.err.println("上传照片失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("上传失败: " + e.getMessage());
        }
    }

    // 获取照片文件
    @GetMapping("/{tireId}/photos/{photoId}")
    public ResponseEntity<Resource> getPhoto(
            @PathVariable Long tireId,
            @PathVariable Long photoId) {

        try {
            System.out.println("获取照片，轮胎ID: " + tireId + ", 照片ID: " + photoId);

            Optional<TirePhoto> photoOpt = tirePhotoService.getPhotoById(photoId);
            if (photoOpt.isEmpty()) {
                System.out.println("照片不存在: " + photoId);
                return ResponseEntity.notFound().build();
            }

            TirePhoto photo = photoOpt.get();

            // 验证照片是否属于指定的轮胎
            if (!photo.getTire().getId().equals(tireId)) {
                System.out.println("照片不属于指定的轮胎");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
            }

            Path filePath = Paths.get(photo.getFilePath());
            System.out.println("照片文件路径: " + filePath);

            if (!Files.exists(filePath)) {
                System.out.println("照片文件不存在: " + filePath);
                return ResponseEntity.notFound().build();
            }

            Resource resource = new UrlResource(filePath.toUri());

            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(photo.getContentType()))
                    .header(HttpHeaders.CONTENT_DISPOSITION,
                            "inline; filename=\"" + photo.getFileName() + "\"")
                    .body(resource);

        } catch (Exception e) {
            System.err.println("获取照片失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.notFound().build();
        }
    }

    // 获取轮胎的所有照片
    @GetMapping("/{tireId}/photos")
    public ResponseEntity<List<TirePhoto>> getTirePhotos(@PathVariable Long tireId) {
        try {
            System.out.println("获取轮胎所有照片，轮胎ID: " + tireId);
            List<TirePhoto> photos = tirePhotoService.getPhotosByTireId(tireId);
            System.out.println("找到 " + photos.size() + " 张照片");
            return ResponseEntity.ok(photos);
        } catch (Exception e) {
            System.err.println("获取轮胎照片列表失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    // 删除照片
    @DeleteMapping("/{tireId}/photos/{photoId}")
    public ResponseEntity<?> deletePhoto(
            @PathVariable Long tireId,
            @PathVariable Long photoId) {

        try {
            System.out.println("删除照片，轮胎ID: " + tireId + ", 照片ID: " + photoId);
            tirePhotoService.deletePhoto(tireId, photoId);
            System.out.println("照片删除成功");
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            System.err.println("删除照片失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("删除失败: " + e.getMessage());
        }
    }
}